package com.joint.web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.base.util.PinyinUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.AnnualBudget;
import com.joint.core.entity.MoneyManager;
import com.joint.core.entity.RebateActivity;
import com.joint.core.service.AnnualBudgetService;
import com.joint.core.service.MoneyManagerService;
import com.joint.core.service.RebateActivityService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by hpj on 2014/9/16.
 */
@ParentPackage("com")
public class AjaxDepartAction extends BaseAdminAction {

    @Resource
    private UsersService usersService;
    @Resource
    private PostService postService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DutyService dutyService;
    @Resource
    private PowerService powerService;
    @Resource
    private CompanyService companyService;

    private Pager pager;
    private Users user;
    private Post post;
    private Duty duty;
    private Department depart;
    private List<Post> postList;
    private ArrayList<Map<String,Object>> postArrayList;
    private ArrayList<Map<String,Object>> dutyArrayList;
    private List<Department> departList;
    private List<Duty> dutyList;
    private List<Users> usersList;
    private List<Department> childList;
    private ArrayList<Map<String, Object>> departmentArrayList;

    private String no;
    private String name;
    private String description;
    private String rowIds;
    private String rowId;
    private String departmentid;
    private String departmentName;
    private String dutyId;
    private String pname;
    protected String companyId;
    protected Company company;


    /**
     * 党政模块定义属性
     */
    private String usersId;
    private String param;
    private String departId;
    @Resource
    private AnnualBudgetService annualBudgetService;
    @Resource
    private RebateActivityService rebateActivityService;
    @Resource
    private MoneyManagerService moneyManagerService;
    private String payDate;


    /**
     * 根据查询项加载JqGrid里的数据
     * @param _search
     * @param params
     * @param filters
     * @return
     */
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& org.apache.commons.lang3.StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(org.apache.commons.lang3.StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    if(field.equals("createDate")){
                                        params.put("createDate", DataUtil.StringToDate(rule.getString("data")));
                                    }else if(field.equals("upParent")){
                                        params.put("parent.name", rule.getString("data"));
                                    }else {
                                        params.put(field, rule.getString("data"));
                                    }
                                }
                            }
                        }
                    }

                }
            }

        }

        return params;
    }
    /**
     * 党政模块定义的方法
     * 根据用户查询用户所属部门
     * @return
     */
    public String departByUsers(){
        company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("parent");
        pager.setOrderType(BaseEnum.OrderType.asc);

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        Users users=new Users();
        if(StringUtils.isNotEmpty(usersId)){
            users=usersService.get(usersId);
        }
        Set<Duty>dutySet=users.getDutySet();
        List<String> idList=Lists.newArrayList();
        for(Duty duty:dutySet){
            if(duty.getState().equals(BaseEnum.StateEnum.Enable)&&duty.getCompany()==company){
                idList.add(duty.getDepartment().getId());
            }

        }

        params.put("id",idList);
        pager = departmentService.findByPagerAndCompany(pager, null, company,  params);
        departList = (List<Department>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Department department:departList){
            rMap=new HashMap<String, Object>();
            rMap.put("id",department.getId()!=null?department.getId():"");
            rMap.put("name",department.getName()!=null?department.getName():"");
            rMap.put("upParent",department.getParent()!=null?department.getParent().getName():"");

            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total = pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records", pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());

    }
    /**
     * 党政模块定义的部门查询
     * 查询一级部门
     * @return
     */
    public String listParty(){
        company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("parent");
        pager.setOrderType(BaseEnum.OrderType.asc);


        //查询所有一级部门
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        params.put("company",company);
        List<Department> departmentList=Lists.newArrayList();
        List<String> idsList=Lists.newArrayList();
        List<Department> parentDepartList=Lists.newArrayList();

        departmentList=departmentService.getList(params);
        for(Department department:departmentList){
            if(department.getParent()==null){
                parentDepartList.add(department);
            }
        }
        //查询在当前时间是否有
        List<Department> departmentMoneyManagerList=Lists.newArrayList();
        Map<String,Object> params1 = new  HashMap<String,Object>();
        List<AnnualBudget> annualBudgetList=Lists.newArrayList();
        List<RebateActivity> rebateActivityList=Lists.newArrayList();
        Set<Department> departments= Sets.newHashSet();//当前登录用户的部门
        Set<Department> departFinished=Sets.newHashSet();//
        params1 = getSearchFilterParams(_search,params1,filters);
        params1.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        params1.put("company",company);
        Boolean flag=false;
        Users users=usersService.getLoginInfo();
        Set<Duty> dutyList=users.getDutySet();
        if(StringUtils.isNotEmpty(param)&&StringUtils.equals(param,"annualbudget")){//一年一次
            params1.put("processState",new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished,FlowEnum.ProcessState.Draft});
            String date=new SimpleDateFormat("yyyy").format(new Date());
            params1.put("annualBudgetYear",date);
            annualBudgetList=annualBudgetService.getList(params1);
            for(AnnualBudget annualBudget:annualBudgetList){
                if(annualBudget.getDepartment()!=null){
                    departFinished.add(annualBudget.getDepartment());
                }
            }
            loop2:for(Duty duty:dutyList){
                if(duty.getState().name().equals("Enable")){
                    if(duty.getDepartment().getParent()==null){
                        if(duty.getPost().getName().equals("退管会专员")==false){
                            continue loop2;
                        }
                        Department d=duty.getDepartment();
                        departments.add(d);
                        LogUtil.info("depart_1:"+d.getName());
                    }else{
                        if(duty.getPost().getName().equals("退管会专员")==false){
                            continue loop2;
                        }
                        Department department2=duty.getDepartment().getParent();
                        LogUtil.info("depart_2:"+department2.getName());
                        departments.add(department2);
                    }
                }

            }
        }else if(StringUtils.isNotEmpty(param)&&StringUtils.equals(param,"rebateactivity")){
            params1.put("processState",new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed,FlowEnum.ProcessState.Draft});
            Department department;
            if(StringUtils.isNotEmpty(departId)){
                department=departmentService.get(departId.trim());
                params1.put("department",department);
            }
            rebateActivityList=rebateActivityService.getList(params1);
            for(RebateActivity rebateActivity:rebateActivityList){
                departFinished.add(rebateActivity.getDepartment());
            }
            loop2:for(Duty duty:dutyList){
                if(duty.getState().name().equals("Enable")) {
                    if (duty.getDepartment().getParent() == null) {
                        if (duty.getPost().getName().equals("退管会专员") == false) {
                            continue loop2;
                        }
                        Department d = duty.getDepartment();
                        departments.add(d);
                    } else {
                        if (duty.getPost().getName().equals("退管会专员") == false) {
                            continue loop2;
                        }
                        Department department2 = duty.getDepartment().getParent();
                        departments.add(department2);
                    }
                }
            }
        }else if(StringUtils.isNotEmpty(param)&&StringUtils.equals(param,"activitymanager")){//不管你是否归档，都可以再次出现
            LogUtil.info("setDuty:"+dutyList.size());
            for(Duty duty:dutyList){
                LogUtil.info("EnumName:"+duty.getState().name());
                if(duty.getState().name().equals("Enable")){
                    LogUtil.info("dutyDepartMent:"+duty.getDepartment().getName());
                    if(duty.getDepartment().getParent()==null){
                        Department d=duty.getDepartment();
                        departments.add(d);
                        LogUtil.info("depart_activity_1:"+d.getName());
                    }else{
                        Department department2=duty.getDepartment().getParent();
                        LogUtil.info("depart_activity_2:"+department2.getName());
                        departments.add(department2);
                    }
                }

            }

        }else if(StringUtils.isNotEmpty(param)&&StringUtils.equals(param,"moneymanager")){
            params1.put("processState",new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished});
            List<String> dateList=Lists.newArrayList();
            if(StringUtils.isNotEmpty(payDate)){
                    for(String s:payDate.split("-")){
                        dateList.add(s.trim());
                    }
                params1.put("registerYear",dateList.get(0));
                params1.put("registerMonth",dateList.get(1));
            }
            if(StringUtils.isNotEmpty(departId)){

            }

            if(StringUtils.isNotEmpty(keyId)){
                MoneyManager moneyManager=moneyManagerService.get(keyId.trim());
                LogUtil.info("processState:"+moneyManager.getProcessState().name());
                LogUtil.info("processState:"+moneyManager.getProcessState().value());
                String year=moneyManager.getRegisterYear();
                String month=moneyManager.getRegisterMonth();

                if(StringUtils.equals(moneyManager.getProcessState().name(),"Backed") && StringUtils.equals(year,dateList.get(0)) && StringUtils.equals(month,dateList.get(1))){
                    departmentMoneyManagerList.add(moneyManagerService.get(keyId.trim()).getDepartment());
                    LogUtil.info("name_1:"+moneyManagerService.get(keyId.trim()).getDepartment().getName());
                }

            }

            List<MoneyManager> moneyManagerList=moneyManagerService.getList(params1);
            for(MoneyManager moneyManager:moneyManagerList){
                departFinished.add(moneyManager.getDepartment());
                LogUtil.info("name_2:"+moneyManager.getDepartment().getName());
            }

            loop2:for(Duty duty:dutyList){
                if(duty.getState().name().equals("Enable")){
                    LogUtil.info("D:"+duty.getDepartment().getName());
                    if(duty.getDepartment().getParent()==null){

                        if(duty.getPost().getName().equals("组织委员")==false){
                            continue loop2;
                        }
                        Department d=duty.getDepartment();
                        departments.add(d);
                        LogUtil.info("depart_m_1:"+d.getName());
                    }else {
                        if (duty.getPost().getName().equals("组织委员") == false) {
                            continue loop2;
                        }
                        Department department2 = duty.getDepartment().getParent();
                        LogUtil.info("depart_m_2" + department2.getName());
                        departments.add(department2);
                    }
                }

            }
        }
        if(departmentMoneyManagerList!=null){
            departFinished.removeAll(departmentMoneyManagerList);
        }
        if(departFinished.size()>0){
            departments.removeAll(departFinished);

        }

        for(Department department:departments){
            idsList.add(department.getId());
            params.put("id",idsList);
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        if(idsList.size()>0){
            pager = departmentService.findByPagerAndCompany(pager, null, company,  params);
            departList = (List<Department>) pager.getList();
            for(Department department:departList){
                rMap=new HashMap<String, Object>();
                rMap.put("id",department.getId());
                rMap.put("name",department.getName());
                dataRows.add(JSONObject.fromObject(rMap));
            }
        }

        long total = pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records", pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());

    }
    /**
     * 返回部门和岗位视图
     * @return
     */
    public String list(){
        company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("parent");
        pager.setOrderType(BaseEnum.OrderType.asc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            if(StringUtils.contains("parent",sidx)){
                pager.setOrderBy("parent_name");
            }
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        pager = departmentService.findByPagerAndCompany(pager, null, company,  params);
        departList = (List<Department>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Department department:departList){
            rMap=new HashMap<String, Object>();
            rMap.put("id",department.getId());
            rMap.put("name",department.getName());
            rMap.put("description",department.getDescription());
            rMap.put("principal",getPrincipal(department.getId()));
            List<Power> powerList=powerService.getByDepartId(department.getId());
            if(dutyService.getPrincipalDuty(department)==null){
                rMap.put("sprincipal","principal");
            }
            else{
                rMap.put("sprincipal","");
            }
            for(Power power:powerList){
                if(power.getPowerDefault()==0){
                   rMap.put("powerId","powerId");
                }
                else{
                   rMap.put("powerId","");
                }
            }
            if(department.getParent()!=null){
                rMap.put("upParent", department.getParent().getName());
                rMap.put("groupId",department.getParent().getId());
                rMap.put("parent",department.getParent().getName());
            }
            else{
                rMap.put("upParent","");
                rMap.put("groupId",department.getId());
                rMap.put("parent","领导层");
            }
            rMap.put("createDate", DataUtil.DateTimeToString(department.getCreateDate()));
            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total = pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records", pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());

    }

    /**
     * 树形部门
     * @return
     */
    public String treeList(){
        company=usersService.getCompanyByUser();
        pager = new Pager(0);
        pager = departmentService.findByPagerAndCompany(pager,null,company,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        departList = (List<Department>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Department department:departList){
            rMap=new HashMap<String, Object>();
            rMap.put("id",department.getId());
            rMap.put("name",department.getName());
            if(department.getParent()!=null){
                rMap.put("level", 1);
                rMap.put("isLeaf", true);
                rMap.put("expanded",true);
            }
            else{
                rMap.put("level", 0);
                rMap.put("isLeaf", false);
                rMap.put("expanded",true);
            }
            rMap.put("createDate", DataUtil.DateTimeToString(department.getCreateDate()));
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("dataRows",dataRows);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 返回部门编辑页面
     * @return
     */
    public String read(){
        company=usersService.getCompanyByUser();
        Map<String,Object> map=null;
        if(StringUtils.isEmpty(keyId)){
            departList =departmentService.getAll();
            departmentArrayList = new ArrayList<Map<String, Object>>();
            for (Department department : departList) {
                map = new HashMap<String, Object>();
                map.put("id", department.getId());
                map.put("name", department.getName());
                departmentArrayList.add(map);
            }
            return "read";
        }
            depart = departmentService.get(keyId);
            pager = new Pager(0);
            pager = departmentService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            departList = (List<Department>) pager.getList();
            departmentArrayList = new ArrayList<Map<String, Object>>();
            for (Department department : departList) {
                map = new HashMap<String, Object>();
                map.put("id", department.getId());
                map.put("selected", "");
                if (depart != null && department.equals(depart.getParent())) {
                    map.put("selected", "selected");
                }
                map.put("name", department.getName());
                departmentArrayList.add(map);
            }

            pager = new Pager();
            pager = postService.findByPagerAndStates(pager, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            postList = (List<Post>) pager.getList();
        return "read";
    }

    /**
     * 部门信息的添加和更新
     * @return
     */
    public String save(){
        Department depart;
        if(StringUtils.isNotEmpty(keyId)){
            depart = departmentService.get(keyId);
        }else {
            depart = new Department();
        }
        depart.setCompany(companyService.get(companyId));
        depart.setName(name);
        depart.setPinYinHead(PinyinUtil.getPinYinHeadChar(name));
        depart.setPinYin(PinyinUtil.getPingYin(name));
        depart.setPname(pname);
        depart.setDescription(description);
        depart.setState(BaseEnum.StateEnum.Enable);
        depart.setBeSystem(0);
        depart.setValue(PinyinUtil.getPinYinHeadChar(name));
        depart.setParent(departmentService.get(departmentid));
        if(StringUtils.isNotEmpty(keyId)){
            departmentService.update(depart);
        }else {
            departmentService.save(depart);
        }

        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    /**
     * 删除部门信息
     * @return
     */
    public String delete() {
        if (StringUtils.isEmpty(keyId)) {
            return ajaxHtmlCallback("200", "请选择部门！","操作状态");
        }
        depart = departmentService.get(keyId);
        Set<Department> departments = depart.getChildren();
        for(Department department:departments){
            if(department.getState().toString().equals("Enable")){
                return  ajaxHtmlCallback("400","该部门有下级部门,请先删除或修改","操作状态");
            }
        }
        List<Power> powerList =  powerService.getByDepartId(keyId);
        if(powerList.size()>0){
            return  ajaxHtmlCallback("400","请先删除关联的职权","操作状态");
        }

        depart.setState(BaseEnum.StateEnum.Delete);
        departmentService.update(depart);
        return ajaxHtmlCallback("200", "删除成功！", "操作状态");

    }

    /**
     * 删除部门成员
     * @return
     */
    public String deleteUser(){
        if(StringUtils.isNotEmpty(keyId)){
            Duty duty=dutyService.get(keyId);
            dutyService.delete(duty);
        }
        return ajaxHtmlCallback("200", "删除成功！", "操作状态");
    }
    /**
     * 部门唯一性校验
     * @return
     */
    public void isUnique(){
        PrintWriter out= null;
        try {
            out=getResponse().getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(departmentService.isUnique(validatePro,keyId,newValue)){
            out.print("true");
        }else{
            out.print("false");
        }

    }
    /**
     *点击部门信息视图的分配岗位弹出的dialog
     * @return
     */
    public String postQuery(){
        List<Power> powerList=null;
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择部门！","操作状态");
        }
        if(powerService.getByDepartId(keyId)!=null){
             powerList=powerService.getByDepartId(keyId);
        }

        List<Post> postLit=null;
        postLit=new ArrayList<Post>();
        if(powerList.size()>0){
            for(Power power:powerList){

                postLit.add(power.getPost());
            }
        }
        Map<String,Object> map;
        postArrayList=new ArrayList<Map<String, Object>>();
        if(postLit!=null && postLit.size()>0){
            for(Post post :postLit){
                map = new HashMap<String, Object>();
                map.put("id",keyId+"-"+post.getId());
                map.put("name",post.getName());
                map.put("checked","");
                Power power=powerService.getPowerByDepartAndPost(departmentService.get(keyId), postService.get(post.getId()));
                if(power.getPowerDefault()==1){
                    map.put("checked","checked");
                }
                postArrayList.add(map);
            }
        }
        return "postQuery";
    }

    /**
     *部门zTree
     */
    public String zTree(){
        company=usersService.getCompanyByUser();
        Pager pager = new Pager(0);
        pager.setPageSize(rows);
        pager.setPageNumber(page);
      //  pager.setOrderBy("orderList");
        pager.setOrderType(BaseEnum.OrderType.asc);
        List<Department> departmentList= (List<Department>) departmentService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        List<JSONObject> treeList = new ArrayList<JSONObject>();
        for(Department per : departmentList){
            Map<String,Object> rMap = new HashMap<String, Object>();
            rMap.put("id",per.getId());
            rMap.put("pId",per.getParent()==null?"":per.getParent().getId());
            rMap.put("pName",per.getName());
            rMap.put("sName",per.getName());
            rMap.put("name",per.getName());
            rMap.put("open", false);
            treeList.add(JSONObject.fromObject(rMap));
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data = new HashMap<String, Object>();
        data.put("data", JSONArray.fromObject(treeList));

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }


    /**
     * 点击设定负责人弹出视图中的确定按钮事件
     * @return
     */
    public String lead(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择部门！","操作状态");
        }
        Set<Post> postSet = new HashSet();
        Set<Duty> dutySet =new HashSet<Duty>();

        Department department =departmentService.get(keyId);
        Duty duty1=dutyService.get(rowIds);
        //将之前的部门负责人变成组员
        Duty duty = dutyService.getPrincipalDuty(department);
        if(duty1.getDutyState()== EnumManage.DutyState.Principal){
            duty.setDutyState(EnumManage.DutyState.Default);
            dutyService.update(duty);
        }else{
            //将组员变成部门负责人
            if(duty!=null){
                duty.setDutyState(EnumManage.DutyState.Default);
                dutyService.update(duty);
            }
            duty1.setDutyState(EnumManage.DutyState.Principal);
            dutyService.update(duty1);
        }
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    /**
     * 点击分配岗位弹出的dialog中的确定按钮事件
     * @return
     */
    public String config(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择部门！","操作状态");
        }
        JSONArray dataRows = JSONArray.fromObject(rowIds);
        Set<Post> postSet = new HashSet<Post>();
        Department department =departmentService.get(keyId);
        for(int i=0;i<dataRows.size();i++){
            JSONObject obj = dataRows.getJSONObject(i);
            String postId = obj.getString("id");
            Post post = postService.get(postId);
            postSet.add(post);
        }
        department.setPostSet(postSet);
        departmentService.update(department);
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    /**
     * 点击设定负责人弹出dialog
     * @return
     */
    public String configView(){
        dutyArrayList = new ArrayList<Map<String, Object>>();
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择负责人！","操作状态");
        }
        depart = departmentService.get(keyId);
        Set<Post> postSet = depart.getPostSet();

        Map<String,Object> map;
        for (Post post:postSet) {
           map=new HashMap<String, Object>();
           map.put("postId",post.getId());
           map.put("postName",post.getName());
           map.put("checked","");
           dutyArrayList.add(map);
        }
        return "configView";
    }

    /**
     * 点击设定负责人弹出dialog中的部门checkBox，查出该部门下对应的岗位和人员
     * @return
     */
    public String configPost(){
        if(StringUtils.isEmpty(rowId)){
            return ajaxHtmlCallback("400", "请选择岗位！","操作状态");
        }
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> rMap = null;
        depart=departmentService.get(keyId);
        post=postService.get(rowId);
        List<Users> usersList = dutyService.getPersons(depart,post);

        for(Users users :usersList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",post.getId()+"-"+users.getId());
            rMap.put("name",post.getName()+"-"+users.getName());
            rMap.put("checked","");
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("state","200");
        data.put("rows", JSONArray.fromObject(dataRows));
        data.put("title","操作状态");
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 点击查看成员弹出的dialog
     * @return
     */
    public String leftView(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择部门！","操作状态");
        }
        Department depart = departmentService.get(keyId);
        dutyList = dutyService.getDutys(depart);
        Map<String,Object> rmap;
        dutyArrayList=new ArrayList<Map<String, Object>>();
        for(Duty duty:dutyList){
            rmap=new HashMap<String, Object>();
            rmap.put("id",duty.getId());
            rmap.put("checked","");
            rmap.put("user", duty.getUsers().getName());
            if (duty.getPower() != null) {
                rmap.put("post", duty.getPower().getPost().getName());
            } else {
                rmap.put("post", "");
            }

            if(duty.getDutyState()== EnumManage.DutyState.Principal){
                rmap.put("checked","checked");
            }
            dutyArrayList.add(rmap);
        }
        return "leftView";
    }

    /**
     * 暂未发现
     * @return
     */
    public String userList(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择部门！","操作状态");
        }
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> rMap = null;
        Department depart = departmentService.get(keyId);
        List<Duty> dutyList = dutyService.getDutys(depart);
        for(Duty duty:dutyList){
            rMap = new HashMap<String, Object>();
            rMap.put("name",duty.getUsers().getName());
            rMap.put("post", duty.getPower().getPost().getName());
            rMap.put("depart",depart.getName());
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("state","200");
        data.put("rows", JSONArray.fromObject(dataRows));
        data.put("title","操作状态");
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 获取当前部门负责人
     * @param departId
     * @return
     */
    public String getPrincipal(String departId){
        Department department = departmentService.get(departId);
        Users users = dutyService.getPrincipal(department);
        if(users != null){
            return users.getName();
        }else{
            return "";
        }
    }

    /**
     * 获取所有部门的组织结构信息
     * @return
     */
    public String organization(){
        Department dep = null;
        Users users=usersService.getLoginInfo();
        Company company=usersService.getCompanyByUser();
        Map<String,Object> rmap=Maps.newHashMap();
        Map<String, Object> data = Maps.newHashMap();
        rmap.put("state", BaseEnum.StateEnum.Enable);
        List<Department> departmentList= (List<Department>) departmentService.findByPagerAndCompany(new Pager(0), null, company,rmap).getList();
        if(departmentList.size()>0){
            for(Department department : departmentList){
                if(department.getParent() != null){
                    continue;
                }
                dep=department;
            }
            data.put("state","200");
            data.put("rows", JSONObject.fromObject(depInfo(dep)));
        }

        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    private Map<String,Object> depInfo(Department dep){
        Map<String,Object> rMap = Maps.newHashMap();
        rMap.put("name",dep.getName());
        rMap.put("id",dep.getId());
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        for (Department depart : dep.getChildren()){
            dataRows.add(JSONObject.fromObject(depInfo(depart)));
        }
        if(dataRows.size() > 0){
            rMap.put("child",JSONArray.fromObject(dataRows));
        }

        return rMap;
    }
    public Pager getPager() {
        return pager;
    }

    public void setPager(Pager pager) {
        this.pager = pager;
    }

    public List<Post> getPostList() {
        return postList;
    }

    public void setPostList(List<Post> postList) {
        this.postList = postList;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }

    public String getKeyId() {
        return keyId;
    }

    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Department getDepart() {
        return depart;
    }

    public void setDepart(Department depart) {
        this.depart = depart;
    }

    public List<Department> getDepartList() {
        return departList;
    }

    public void setDepartList(List<Department> departList) {
        this.departList = departList;
    }

    public String getRowIds() {
        return rowIds;
    }

    public void setRowIds(String rowIds) {
        this.rowIds = rowIds;
    }

    public ArrayList<Map<String, Object>> getPostArrayList() {
        return postArrayList;
    }

    public void setPostArrayList(ArrayList<Map<String, Object>> postArrayList) {
        this.postArrayList = postArrayList;
    }

    public List<Duty> getDutyList() {
        return dutyList;
    }

    public void setDutyList(List<Duty> dutyList) {
        this.dutyList = dutyList;
    }

    public String getDepartmentid() {
        return departmentid;
    }

    public void setDepartmentid(String departmentid) {
        this.departmentid = departmentid;
    }

    public ArrayList<Map<String, Object>> getDutyArrayList() {
        return dutyArrayList;
    }

    public void setDutyArrayList(ArrayList<Map<String, Object>> dutyArrayList) {
        this.dutyArrayList = dutyArrayList;
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

    public String getRowId() {
        return rowId;
    }

    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

    public List<Department> getChildList() {
        return childList;
    }

    public void setChildList(List<Department> childList) {
        this.childList = childList;
    }

    public Duty getDuty() {
        return duty;
    }

    public void setDuty(Duty duty) {
        this.duty = duty;
    }

    public ArrayList<Map<String, Object>> getDepartmentArrayList() {
        return departmentArrayList;
    }

    public void setDepartmentArrayList(ArrayList<Map<String, Object>> departmentArrayList) {
        this.departmentArrayList = departmentArrayList;
    }

    public String getDutyId() {
        return dutyId;
    }

    public void setDutyId(String dutyId) {
        this.dutyId = dutyId;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public String getUsersId() {
        return usersId;
    }

    public void setUsersId(String usersId) {
        this.usersId = usersId;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getPayDate() {
        return payDate;
    }

    public void setPayDate(String payDate) {
        this.payDate = payDate;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}
